﻿using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using System;
using System.Diagnostics;

namespace FantomNext.Views;

public partial class MainView : UserControl
{
    public MainView()
    {
        InitializeComponent();
    }

    private void Button_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        int value1 = IntParseDefault(PART_TextBox1.Text, 0);
        int value2 = IntParseDefault(PART_TextBox2.Text, 0);
        var shapePresenter = GlobalData.ScenePresenter.CreateRect(value1, value2, 100, 100);

        //GlobalData.ScenePresenter.CreateSelection(shapePresenter);

    }
    private void Button_Click2(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        Test();
    }

    private int IntParseDefault(string content, int defaultValue = 0)
    {
        var result = defaultValue;
        if (int.TryParse(content, out result)) return result;
        else return defaultValue;

    }

    public void Test()
    {
        var filePath = @"G:\fanbaldir\test\test.png";
        var visual = this;
        ExportImage(visual, filePath);
    }

    /// <summary>
    /// 将控件导出为图片。
    /// </summary>
    /// <param name="visual">控件对象。</param>
    /// <param name="filePath">导出的文件路径。</param>
    public void ExportImage(Visual visual, string filePath)
    {
        // 获得控件的尺寸。
        var width = (int)visual.Bounds.Width;
        var height = (int)visual.Bounds.Height;

        var visualBrush = new VisualBrush(this);

        var renderTargetBitmap = new RenderTargetBitmap(new PixelSize(width, height));
        using var canvas = renderTargetBitmap.CreateDrawingContext(false);

        canvas.DrawRectangle(visualBrush, null, new Rect(0, 0, width, height));
        renderTargetBitmap.Save(filePath);
    }
}
